#!/usr/bin/env python
# encoding: utf-8
"""
bridge.py

Created by Steven Hepting on 2008-04-29.
Copyright (c) 2008 ProtoSpec Engineering. All rights reserved.
"""

import sys
import os
import twisted
import serial
import time
import logging
import re

import mail
import log
log = logging.getLogger()

# Set the environment variable so the import works correctly
sys.path.append('/home/steven/Projects/ProtoSpec/web/django_site')
os.environ["DJANGO_SETTINGS_MODULE"]="settings"
from monitor.models import Sensor, Datum

def ser_connect():
    # Find the filename to use
    for filename in os.listdir('/dev'):
        if re.compile("tty.usbserial").match(filename):
            arduino_file = "/dev/%s" % filename
    try: arduino_file
    except NameError:
        print "Arduino board not found. Connect Arduino and try again."
        sys.exit(1)
    else:
        print "No exception"
        # Make the serial connection to the base Arduino
        while(True):
            try:
                ser = serial.Serial(arduino_file, 115200, timeout=0)
                log.debug("Connected to %s" % arduino_file)
                return ser
            except serial.serialutil.SerialException, e:
                log.error(e)
                log.info("Please connect Arduino board and try again.")
                time.sleep(10)

            
def flash(ser):
    # Flash the led on the Arduino
    for x in range(3):
        on(ser)
        time.sleep(5)
        off(ser)
        time.sleep(1)
        
def on(ser):
    """Send a message to the Arduino to turn on"""
    msg = "o\n"
    ser.write(msg)
    log.debug("Wrote %s" % msg.strip())
    
def off(ser):
    """Send a message to the Arduino to turn on"""
    msg = "f\n"
    ser.write(msg)
    log.debug("Wrote %s" % msg.strip())
    
def main():
    """while 1:
    	while (ser.inWaiting() == 0):
    	    # Keep this loop from overloading the cpu
    		time.sleep(.1)
    	line = ser.readlines(2)
    	ser.flushInput
        in_data.append(line[0].strip())
        # Print once every 5 seconds
        this_time = time.time()"""
    #try:
    ser = ser_connect()
    flash(ser)
    #finally:
    ser.close()





if __name__ == '__main__':
	main()